package cn.lxb.emall.gw.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyRequestBodyGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyResponseBodyGatewayFilterFactory;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.fasterxml.jackson.databind.ObjectMapper;

import reactor.core.publisher.Mono;

@Configuration
public class RotesConfiguration {
	
	@Autowired
	EncryptConfig encryptConfig;

	@Bean
	public RouteLocator routes(RouteLocatorBuilder routeLocatorBuilder, ObjectMapper objectMapper,
			ConditionalModifyResponseBodyGatewayFilterFactory msFactory) {
		ModifyRequestBodyGatewayFilterFactory.Config mrConfig = new ModifyRequestBodyGatewayFilterFactory.Config();
		mrConfig.setRewriteFunction(String.class, String.class, (t, r) -> Mono.just(encryptConfig.decodeRequest(t, r)));
		ConditionalModifyRequestBodyGatewayFilterFactory mrFactory = new ConditionalModifyRequestBodyGatewayFilterFactory();
		mrFactory.setCondition(encryptConfig::decodeCondition);
		GatewayFilter mrFilter = mrFactory.apply(mrConfig);

		ModifyResponseBodyGatewayFilterFactory.Config msConfig = new ModifyResponseBodyGatewayFilterFactory.Config();
		msFactory.setCondition(encryptConfig::encodeCondition);
		msConfig.setRewriteFunction(String.class, String.class, (t, r) -> Mono.just(encryptConfig.encodeResponse(t, r)));
		GatewayFilter msFilter = msFactory.apply(msConfig);

		return routeLocatorBuilder.routes()
				.route("user", r -> r.path("/user/**")
						.filters(f -> f.rewritePath("/user", "").filter(mrFilter).filter(msFilter,-2)).uri("lb://user"))
				.build();
	}

}
